package com.rui.sideup.module.easyexcel.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.rui.sideup.module.easyexcel.*;
import com.rui.sideup.module.easyexcel.entity.RowRange;
import com.rui.sideup.module.easyexcel.entity.Student;
import com.rui.sideup.module.easyexcel.utils.ExcelUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * excel方法实现
 *
 * @author ZhangRui
 * @date 2022/11/22 13:29
 **/
@Service
public class EasyExcelServiceImpl implements EasyExcelService {

    /**
     * 基础下载
     */
    @Override
    public void download(HttpServletResponse response) throws IOException {

        String message = "下载文件失败";
        String filename = "学生信息.xlsx";

        try {
            // 设置响应头
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
            // 类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("utf-8");

            // 获取导出数据
            List<Student> students = DataReady.listStudent();

            // 合并策略
            Map<String,List<RowRange>> rowRangeMap = addMerStrategy(students);
            MergeStrategy mergeStrategy = new MergeStrategy(rowRangeMap);

            // 数据导出
            EasyExcel.write(response.getOutputStream(), Student.class)
                    .registerWriteHandler(ExcelUtils.setHorizontalCellStyleStrategy())
                    .registerWriteHandler(mergeStrategy)
                    .sheet("学生信息").doWrite(students);

        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSON.toJSON(message));
        }
    }


    /**
     * 添加合并策略
     */
    private Map<String, List<RowRange>> addMerStrategy(List<Student> students) {

        // key: 表示需要合并的列  value: 表示该列需要合并的行集合
        Map<String, List<RowRange>> strategyMap = new HashMap<>();

        // 前一条数据。 （用于判断是否需要合并）
        Student preStudent = null;
        for (int i = 0; i < students.size(); i++) {

            Student student = students.get(i);
            if (preStudent != null) {
                // 年级合并
                if (student.getGrade().equals(preStudent.getGrade())) {
                    fillStrategyMap(strategyMap, "0", i);
                }
            }
            preStudent = student;
        }

        return strategyMap;
    }

    /**
     * 计算需要合并的行
     *
     */
    public static void fillStrategyMap(Map<String, List<RowRange>> strategyMap, String key, int index) {

        List<RowRange> rowRangeList = strategyMap.get(key) == null ? new ArrayList<>() : strategyMap.get(key);

        // 判断是否新增分段
        boolean flag = false;

        for (RowRange dto : rowRangeList) {
            //分段list中是否有end索引是上一行索引的，如果有，则索引+1
            if (dto.getEnd() == index) {
                dto.setEnd(index + 1);
                flag = true;
            }
        }
        //如果没有，则新增分段
        if (!flag) {
            rowRangeList.add(new RowRange(index, index + 1));
        }
        strategyMap.put(key, rowRangeList);
    }

}
